package com.baiytfp.hf.HFDataExchange.action.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.baiytfp.hf.baiytfp.framework.base.BaseService;
import com.baiytfp.hf.HFDataExchange.common.model.base.HFSysParams;

import org.springframework.stereotype.Service;

import com.baiytfp.hf.baiytfp.common.db.HFPager;
import com.baiytfp.hf.baiytfp.hfutils.HFDBHelper;
import com.baiytfp.hf.baiytfp.hfutils.HFMap;
import com.baiytfp.hf.HFDataExchange.action.dao.UserDAOImpl;
import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.model.table.User_account;

@Service
public class UserService extends BaseService {

	@Resource(name= HFSysParams.DB_TYPE + "UserDAOImpl")
    private UserDAOImpl userDAO;


	/**
	 * 通过user_code获得用户信息
	 * @param user_code
	 * @return
	 * @throws Exception 
	 */
	public User_account getUserByUserCode(String user_code) throws Exception {
		return HFDBHelper.read(TableName.USER_ACCOUNT, " WHERE user_code=? ", User_account.class, user_code);
	}
	
	/**
	 * 更新
	 * @param userAccount
	 * @return
	 * @throws Exception
	 */
	public long udateUser(User_account userAccount)throws Exception {
		return HFDBHelper.update(TableName.USER_ACCOUNT, " WHERE user_code=? ", userAccount, userAccount.getUser_code());
	}

	public List<Map> getUserList(HFPager hfPager)
			throws Exception {

		Map<String, String> map = hfPager.getParams();

		StringBuffer sWhere = new StringBuffer(" where 1 =1 ");
		StringBuffer sql = new StringBuffer("select ua.is_admin, d.dept_name, ui.* from " + TableName.USER_ACCOUNT
				+  " ua left join " + TableName.USER_INFO + " ui on ua.user_code=ui.user_code "
				+  " left join " + TableName.USER_DEPT + " ud on ua.user_code=ud.user_code and ud.is_current=1 "
				+  " left join " + TableName.DEPT + " d on ud.dept_id=d.tree_id ");

		List<String> params = new ArrayList<String>();

		if (!"".equals(hfPager.getParam("user_name"))) {
			if (sWhere.length() > 0) {
				sWhere.append(" and ");
			}
			sWhere.append(" user_name like ?");
			params.add("%" + HFMap.getIstance().getString(map, "user_name") + "%");
		}
		if (!"".equals(hfPager.getParam("user_code"))) {
			if (sWhere.length() > 0) {
				sWhere.append(" and ");
			}
			sWhere.append(" ui.user_code like ?");
			params.add("%" + HFMap.getIstance().getString(map, "user_code") + "%");
		}
		if (!"".equals(hfPager.getParam("dept_id"))) {
			if (sWhere.length() > 0) {
				sWhere.append(" and ");
			}
			sWhere.append(" ud.dept_id = ?");
			params.add(HFMap.getIstance().getString(map, "dept_id"));
		}


		List<Map> list = HFDBHelper.list_split(sql.toString() + sWhere.toString() + hfPager.getOrderBy(), Map.class, hfPager, params.toArray());

		return list;
	}
}
